package cn.hcbycloud.common.jwt.service.encryptionkey;

import cn.hcbycloud.common.core.exception.CustomizeException;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author gaoh
 * @desc 获取密钥对字符串接口
 * @date 2022年01月13日 上午 12:55
 */
public abstract class BaseGenerateJwtKeyService {

    /**
     * 获取公钥字符串
     *
     * @return
     */
    public abstract String getJwtPublicKeyStr();

    /**
     * 获取私钥字符串
     *
     * @return
     */
    public abstract String getJwtPrivateKeyStr();

    /**
     * 获取私钥对象
     *
     * @return
     */
    public PrivateKey getPrivateKey() {
        try {
            byte[] result = Base64.getDecoder().decode(this.getJwtPrivateKeyStr());
            PKCS8EncodedKeySpec priPksc8 = new PKCS8EncodedKeySpec(result);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(priPksc8);
        } catch (Exception e) {
            throw new CustomizeException("无法获取私钥对象", e);
        }
    }

    /**
     * 获取公钥对象
     *
     * @return
     */
    public PublicKey getPublicKey() {
        byte[] result = Base64.getDecoder().decode(this.getJwtPublicKeyStr());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(result);
        try {
            return KeyFactory.getInstance("RSA").generatePublic(keySpec);
        } catch (Exception e) {
            throw new CustomizeException("无法获取公钥对象", e);
        }
    }
}